using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Collections.Specialized;

namespace GeneticProgrammingUI_CS
{
    public partial class frmMain : Form
    {
        // NEED TO MAKE THIS DYNAMIC FILE SELECTION.
        public static String DEFAULT_DIR = "C:\\geneticprogrammingUITest\\";
        public static String SETTINGS_FILE = "settings.properties";
        public static String DATA_FILE = "training.data";
        String GPPROG = "gpStart.bat";// this bat will have the actual java run process

        DataTable dataTable;

        public ArrayList xValue;
        public ArrayList yValue;

        public frmMain()
        {
            InitializeComponent();
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            loadToolTips();
            loadSettings();
            loadTrainingData();
        }

        /**
         * This Method will load the Data in the Grid View.
         **/
        private void loadTrainingData()
        {   // Setting DataTable.
            dataTable = new DataTable(); // we will bind this table with datagridview.
            DataColumn columnX = new DataColumn();// data column x
            DataColumn columnY = new DataColumn();// data column y
            
            columnX.ColumnName="x";
            columnY.ColumnName="y";
            
            columnX.DataType=System.Type.GetType("System.Double");
            columnY.DataType = System.Type.GetType("System.Double");

            dataTable.Columns.Add(columnX);
            dataTable.Columns.Add(columnY);

            //Adding Primary Key constrain.
            DataColumn[] primaryKey = new DataColumn[1];
            primaryKey[0] = dataTable.Columns["x"];
            dataTable.PrimaryKey = primaryKey;

            readTrainingDataFromFile(dataTable);
            
            dataGridView.DataSource = dataTable;

        }

        /**
         * This Method will read the Data from Text file and load it on the DataTable
         * */
        private void readTrainingDataFromFile(DataTable dataTable)
        {
            FileStream file = new FileStream(DEFAULT_DIR + DATA_FILE, FileMode.OpenOrCreate, FileAccess.Read);
            StreamReader sr = new StreamReader(file);
            String data = sr.ReadLine();
            xValue = new ArrayList();
            yValue = new ArrayList();

            while (data != null && !data.Equals(""))
            {
                String[] datarow = data.Split(',');

                // Adding to the row
                DataRow row = dataTable.NewRow();
                row["x"] = System.Double.Parse(datarow[0].Trim());
                xValue.Add(System.Double.Parse(datarow[0].Trim()));
                row["y"] = System.Double.Parse(datarow[1].Trim());
                yValue.Add(System.Double.Parse(datarow[1].Trim()));
                dataTable.Rows.Add(row);

                data = sr.ReadLine();
            }
            sr.Close();
            file.Close();

        }

        /**
         * Adds Tool Tip detail for the controls in use.
         * */
        private void loadToolTips()
        {
            toolTip.SetToolTip(btnSettingsReload, "Reloads from the Settings File");
            toolTip.SetToolTip(btnSettingsSave, "Saves to the Setting File");
            toolTip.SetToolTip(btnQuit, "Exits this Program");
            toolTip.SetToolTip(btnStartGP, "Starts the Genetic Programming Process");
            toolTip.SetToolTip(btnTrainingDataReload, "Reloads from the Data File");
            toolTip.SetToolTip(btnTrainingDataSave, "Saves to the Data File");
        }

        /**
         * This Method will load the conents from the "c:\settings.properties" to text boxes.
         **/
        private void loadSettings()
        {
            // NEED TO UPDATE THIS TO HAVE DINAMIC LOCATION.

            FileStream file = new FileStream(DEFAULT_DIR + SETTINGS_FILE, FileMode.OpenOrCreate, FileAccess.Read);
            StreamReader sr = new StreamReader(file);
            String propAttribute = sr.ReadLine();
            
            NameValueCollection propMap=new NameValueCollection();
   
            while (propAttribute != null && !propAttribute.Equals(""))
            {
                String[] propElement = propAttribute.Split('='); // split the line
                propMap.Add((propElement[0].Trim()), (propElement[1].Trim())); // putting it into collection.
                propAttribute = sr.ReadLine();
            }
            sr.Close();
            file.Close();
            //*** Putting in the text boxes ***//
            tbPopulation.Text = propMap.Get("maxPopulation");
            tbCrossoverCount.Text = propMap.Get("crossoverCount");
            tbMutateCount.Text = propMap.Get("mutateCount");
            tbSurvivorCount.Text = propMap.Get("trimSurvivorCount");
            tbTreeHeight.Text = propMap.Get("maxTreeHeight");

            trackBarCrossoverCount.Value = (int)((double.Parse(tbCrossoverCount.Text.ToString())/(double.Parse(tbPopulation.Text.ToString())))*100);
            trackBarMutateCount.Value = (int)((double.Parse(tbMutateCount.Text.ToString()) / (double.Parse(tbPopulation.Text.ToString())))*100);
            trackBarSurvivorCount.Value =(int) ((double.Parse(tbSurvivorCount.Text.ToString()) / (double.Parse(tbPopulation.Text.ToString())))*100);

        }

        /**
         * This Method will save the current conents from the text boxes to the settings file.
         **/
        private void saveSettings()
        {
            FileStream file = new FileStream(DEFAULT_DIR+SETTINGS_FILE, FileMode.Create, FileAccess.Write);
            StreamWriter sw = new StreamWriter(file);

            sw.WriteLine("maxPopulation = "+tbPopulation.Text);
            sw.WriteLine("trimSurvivorCount = " + tbSurvivorCount.Text);
            sw.WriteLine("crossoverCount = " + tbCrossoverCount.Text);
            sw.WriteLine("mutateCount = " + tbMutateCount.Text);
            sw.WriteLine("maxTreeHeight = " + tbTreeHeight.Text);
            sw.Flush();
            sw.Close();
            file.Close();
        }

        private void Button1_Click(object sender, EventArgs e)
        {
            loadSettings();
        }

        private void Button4_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnSettingsSave_Click(object sender, EventArgs e)
        {
            saveSettings();
        }

        private void Button6_Click(object sender, EventArgs e)
        {
            loadTrainingData();
        }

        private void btnTrainingDataSave_Click(object sender, EventArgs e)
        {
            FileStream file = new FileStream(DEFAULT_DIR + DATA_FILE, FileMode.Create, FileAccess.Write);
            StreamWriter sw = new StreamWriter(file);
            String x, y;
            for (int i = 0; i < dataTable.Rows.Count; i++)
            {
                x = dataTable.Rows[i]["x"].ToString();
                y = dataTable.Rows[i]["y"].ToString();
                if (x == null || x.Equals(""))x="0";
                if (y == null || y.Equals("")) y = "0";
                sw.WriteLine( x+ ", " + y);
            }
            sw.Flush();
            sw.Close();
            file.Close();
        }

        private void btnStartGP_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start(DEFAULT_DIR+GPPROG); //MR comment out for now
            frmProcess fp=new frmProcess(xValue,yValue);
            fp.Visible = true;
        }

        private void trackBarSurvivorCount_Scroll(object sender, EventArgs e)
        {
            tbSurvivorCount.Text = ""+(int)((trackBarSurvivorCount.Value/100.0)*double.Parse(tbPopulation.Text.ToString()));
        }

        private void trackBarCrossoverCount_Scroll(object sender, EventArgs e)
        {
            tbCrossoverCount.Text = "" + (int)((trackBarCrossoverCount.Value / 100.0) * double.Parse(tbPopulation.Text.ToString()));
        }

        private void trackBarMutateCount_Scroll(object sender, EventArgs e)
        {
            tbMutateCount.Text = ""+ (int)((trackBarMutateCount.Value/100.0)*double.Parse(tbPopulation.Text.ToString()));
        }

        private void popChangeReCalc()
        {
            tbSurvivorCount.Text = "" + (int)((trackBarSurvivorCount.Value / 100.0) * double.Parse(tbPopulation.Text.ToString()));
            tbCrossoverCount.Text = "" + (int)((trackBarCrossoverCount.Value / 100.0) * double.Parse(tbPopulation.Text.ToString()));
            tbMutateCount.Text = "" + (int)((trackBarMutateCount.Value / 100.0) * double.Parse(tbPopulation.Text.ToString()));
        }

        private void tbPopulation_TextChanged(object sender, EventArgs e)
        {
            popChangeReCalc();
        }

    }
}